﻿using Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;

namespace Business
{
    public class CustomerBiz
    {
        public int SaveItem(Customer item)
        {
            var dbContext = new Context();

            dbContext.Customers.Add(item);
            dbContext.SaveChanges();

            return item.Id;
        }

        public void UpdateItem(Customer item)
        {
            var dbContext = new Context();
            dbContext.Entry(item).State = EntityState.Modified;
            dbContext.SaveChanges();
        }

        public Customer LoadItem(int id)
        {
            var dbContext = new Context();
            return (from item in dbContext.Customers
                    where item.Id == id
                    select item).First();
        }

        public void RemoveItem(List<Customer> items)
        {
            var dbContext = new Context();

            string ids = string.Empty;

            foreach (var item in items)
            {
                ids += item.Id + ",";
            }

            if (ids.EndsWith(","))
            {
                ids = ids.Substring(0, ids.Length - 1);

                string deleteCommand = string.Format(Constants.DeleteCommand, "Customer", ids);
                dbContext.Database.ExecuteSqlCommand(deleteCommand);
            }    
        }

        public List<Customer> LoadItems()
        {
            var dbContext = new Context();
            return (from item in dbContext.Customers
                    orderby item.FullName
                    select item).ToList();
        }

        public List<string> LoadAllCustomerName()
        {
            var dbContext = new Context();
            return (from item in dbContext.Customers
                    orderby item.FullName
                    select item.FullName).ToList();
        }

        public List<Customer> SearchCustomerByName(string name)
        {
            var dbContext = new Context();
            return (from item in dbContext.Customers
                    where item.FullName.ToLower().Contains(name.ToLower())
                    orderby item.FullName
                    select item).ToList();
        }

        public List<SearchCustomerResult> SearchCustomer(int id)
        {
            var customerParam = new SqlParameter { ParameterName = "@Customer", Value = DBNull.Value, DbType = DbType.Int32 };

            customerParam.Value = id;

            var dbContext = new Context();
            var data = dbContext.Database.SqlQuery<SearchCustomerResult>("SearchCustomerInfo @Customer", customerParam).ToList();

            return data;
        }
    }
}
